<template>
  <div class="product-form">
    <el-card>
      <template #header>
        <h3>{{ isEdit ? '编辑商品' : '添加商品' }}</h3>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :min="0" />
        </el-form-item>

        <el-form-item label="商品库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>

        <el-form-item label="所属商店" prop="shopId">
          <el-select v-model="form.shopId">
            <el-option
              v-for="shop in shops"
              :key="shop.id"
              :label="shop.name"
              :value="shop.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            rows="4"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { productApi } from '@/api/product'
import { shopApi } from '@/api/shop'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const shops = ref([])

const isEdit = computed(() => route.params.id)

const form = ref({
  name: '',
  price: 0,
  stock: 0,
  shopId: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  shopId: [{ required: true, message: '请选择所属商店', trigger: 'change' }]
}

const fetchShops = async () => {
  try {
    const data = await shopApi.getShops()
    shops.value = data.data
    console.log('shops:',shops.value)
  } catch (error) {
    console.error('获取商店列表失败:', error)
  }
}

const fetchProduct = async (id) => {
  try {
    const data = await productApi.getProduct(id)
    form.value = data
  } catch (error) {
    console.error('获取商品详情失败:', error)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate()
  
  try {
    if (isEdit.value) {
      await productApi.updateProduct(route.params.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await productApi.createProduct(form.value)
      ElMessage.success('创建成功')
    }
    router.push('/products')
  } catch (error) {
    console.error('保存商品失败:', error)
  }
}

onMounted(async () => {
  await fetchShops()
  if (isEdit.value) {
    await fetchProduct(route.params.id)
  }
})
</script>

<style scoped>
.product-form {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}
</style> 